﻿using IOP.SgrA;
using IOP.SgrA.Input;
using IOP.SgrA.SilkNet.Vulkan;
using Silk.NET.Vulkan;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace VkSample413
{
    public class SecondaryRenderingMiddleware : IProductionLineMiddleware<SecondaryVulkanRenderGroup>
    {
        public void Invoke(SecondaryVulkanRenderGroup group, RenderingProductionLineDelegate<SecondaryVulkanRenderGroup> next)
        {
            var camera = group.Camera;
            var view = camera.ViewMatrix;
            var project = camera.ProjectionMatrix;
            var cmd = group.SecondaryCommandBuffer;
            var depthOffsetFlag = group.GetCustomPropery<int>("depthOffsetFlag");

            CommandBufferInheritanceInfo info = new CommandBufferInheritanceInfo
            {
                Framebuffer = group.Framebuffer.RawHandle,
                OcclusionQueryEnable = false,
                RenderPass = group.RenderPass.RawHandle,
                Subpass = 0
            };
            cmd.Reset();
            cmd.Begin(CommandBufferUsageFlags.CommandBufferUsageOneTimeSubmitBit | 
                CommandBufferUsageFlags.CommandBufferUsageRenderPassContinueBit, info);
            cmd.BindPipeline(PipelineBindPoint.Graphics, group.Pipeline);
            cmd.SetDepthBias(0, 0, 0);
            foreach (var item in group.GetContexts())
            {
                item.SetViewMatrix(in view);
                item.SetProjectionMatrix(in project);
                group.ItemProductionLine(item);

                switch (depthOffsetFlag)
                {
                    case 1:
                        cmd.SetDepthBias(-1, -3, -2);
                        break;
                    case 2:
                        cmd.SetDepthBias(1, 3, 2);
                        break;
                    default:
                        cmd.SetDepthBias(0, 0, 0);
                        break;
                }
            }
            group.SecondaryCommandBuffer.End();
        }
    }
}
